package com.ziytek.web.citizen.util;

import com.github.luben.zstd.Zstd;
import com.ziytek.web.citizen.constant.NumConstant;

import java.nio.ByteBuffer;

/**
 * @author fengh
 */
public class CompressionUtils {

    public static byte[] compressWithZstd(byte[] data) {
        byte[] compressed = Zstd.compress(data);
        // 创建包含原始长度的新字节数组
        var buffer = ByteBuffer.allocate(NumConstant.INT_EIGHT + compressed.length);
        // 前8字节存储原始长度
        buffer.putLong(data.length);
        buffer.put(compressed);
        return buffer.array();
    }

    public static byte[] decompressWithZstd(byte[] compressedDataWithHeader) {
        var buffer = ByteBuffer.wrap(compressedDataWithHeader);
        // 读取压缩时存储的原始长度
        var originalSize = buffer.getLong();

        byte[] compressedData = new byte[compressedDataWithHeader.length - NumConstant.INT_EIGHT];
        buffer.get(compressedData);

        return Zstd.decompress(compressedData, (int) originalSize);
    }
}